<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\model\SalesmanFinanceDaily;
use app\Request;
use app\admin\model\Salesman as SalesmanModel;
use think\facade\Db;

class Salesman extends Controller
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index() {
        $model = new SalesmanModel();
        $data = input();

        return $model->dataList($data);
    }

    /**
     * 业务员 修改或者创建
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function create() {
        $paramBase = input('post.');

        $validate = new \app\admin\validate\Salesman();
        $id = $paramBase['id'] ?? '';
        if ($id) {
            if (!$validate->scene('edit')->check($paramBase)) {
                return fail($validate->getError());
            }
        } else {
            if (!$validate->scene('create')->check($paramBase)) {
                return fail($validate->getError());
            }
        }

        if (!empty($paramBase['password'])) {
            $paramBase['password'] = password_hash($paramBase['password'], PASSWORD_DEFAULT);
        }
        $salesmanModel = new SalesmanModel();
        return $salesmanModel->saveData($paramBase);
    }

    /**
     * 业务员下拉数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllSalesman() {
        $model = new SalesmanModel();
        $result = $model->salesmanMap();
        return success('操作成功', $result);
    }

    /**
     * 关联代理商详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function agentDetail() {
        $model = new SalesmanModel();
        $id = input('id', '');
        if (!$id) {
            return fail('业务员ID参数不能为空');
        }
        $result = $model->agentDetail($id);
        if ($result) {
            return success('操作成功', $result);
        }
        return fail('操作失败');
    }
}